package com.bt.lms.utils;

/**
 * 转换工具类
 *
 * @author 徐大永
 */
public class Convert {

    /**
     * short转byte
     *
     * @param s 要转的数字
     * @return 转成的byte数组
     */
    public static byte[] shortToBytes(short s) {
        byte[] b = new byte[2];
        for (int i = 0; i < 2; i++) {
            int offset = 16 - (i + 1) * 8; //因为byte占4个字节，所以要计算偏移量
            b[i] = (byte) ((s >> offset) & 0xff); //把16位分为2个8位进行分别存储
        }
        return b;
    }

    /**
     * long转byte
     *
     * @param l 要转的long
     * @return 转成的byte数组
     */
    public static byte[] longToBytes(long l) {
        byte[] b = new byte[8];
        for (int i = 0; i < 8; i++) {
            int offset = 64 - (i + 1) * 8; //因为byte占4个字节，所以要计算偏移量
            b[i] = (byte) ((l >> offset) & 0xff); //把16位分为2个8位进行分别存储
        }
        return b;
    }

    /**
     * int转byte
     *
     * @param i 要转的int
     * @return 转成的byte数组
     */
    public static byte[] intToBytes(int i) {
        byte[] b = new byte[4];
        for (int j = 0; j < 4; j++) {
            int offset = 32 - (j + 1) * 8; //因为byte占4个字节，所以要计算偏移量
            b[j] = (byte) ((i >> offset) & 0xff); //把16位分为2个8位进行分别存储
        }
        return b;
    }

    /**
     * byte数组转int
     *
     * @param bytes 要转的byte数组
     * @return 转成的int
     */
    public static int bytesToInt(byte[] bytes) {

        int value = 0;
        for (int i = 0; i < 4; i++) {
            int shift = (3 - i) * 8;
            value += (bytes[i] & 0xFF) << shift;
        }
        return value;

    }

    /**
     * byte数组转short
     * @param bytes 要转的byte数组
     * @return 转好的值
     */
    public static short bytesToShort(byte[] bytes) {
        short l = 0;
        for (int i = 0; i < 2; i++) {
            l<<=8; //<<=和我们的 +=是一样的，意思就是 l = l << 8
            l |= (bytes[i] & 0xff); //和上面也是一样的  l = l | (b[i]&0xff)
        }
        return l;
    }

    /**
     * byte数组转long
     * @param bytes 要转的byte数组
     * @return 转好的值
     */
    public static Long bytesToLong(byte[] bytes) {
        long  values = 0;
        for (int i = 0; i < 8; i++) {
            values <<= 8; values|= (bytes[i] & 0xff);
        }
        return values;
    }

}